<!--
 * @description:
 * @param:
 * @return:
 * @author: Seven
-->
<template>
  <a-drawer v-model:visible="visible" :title="model.id ? '工单详情' : '新增工单'" placement="right" :width="450" :destroyOnClose="true">
    <a-form ref="formRef" :model="model" :rules="rules" :label-col="{ span: 5 }" @finish="onFinish">
      <a-form-item label="归属站点" name="stationCode">
        <a-select v-model:value="model.stationCode" allowClear :disabled="true">
          <template v-for="(item, index) in stationList" :key="index">
            <a-select-option :value="item.stationCode">
              {{ item.name }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="处理方式" name="handleType">
        <a-select v-model:value="model.handleType" allowClear placeholder="请选择处理方式" :disabled="isDisabled">
          <a-select-option :value="1"> 自主处理 </a-select-option>
          <a-select-option :value="2"> 领导确认 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="工单类型" name="orderType">
        <a-select v-model:value="model.orderType" allowClear placeholder="请选择工单类型" :disabled="isDisabled">
          <template v-for="(item, index) in odrerTypeList" :key="index">
            <a-select-option :value="Number(item.value)">
              {{ item.label }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="工单内容" name="orderDetail">
        <a-input v-model:value="model.orderDetail" allowClear placeholder="请输入工单内容" :disabled="isDisabled" />
      </a-form-item>
      <!-- <a-form-item label="处理人" name="assignTo">
        <a-select v-model:value="model.assignTo" allowClear placeholder="请选择处理人" :disabled="isDisabled">
          <template v-for="(item, index) in userList" :key="index">
            <a-select-option :value="item.username">
              {{ item.realname }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item> -->
      <a-form-item label="附件">
        <a-upload
          name="file"
          :action="ossAction"
          :multiple="false"
          v-model:file-list="fileList"
          list-type="picture-card"
          :headers="tokenHeader"
          :showUploadList="true"
          :disabled="isDisabled"
          @change="handleUploadChange"
        >
          <div class="flex items-center justify-end upload-form-item" title="点击上传文件" v-if="!model.id">
            <i class="ico"></i>
            <span>上传</span>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="第三方维修" name="needRepair">
        <a-checkbox v-model:checked="model.needRepair" disabled="true" />
      </a-form-item>
      <a-form-item label="维修金额" name="repairePrice" v-if="model.needRepair">
        <a-input v-model:value="model.repairePrice" :disabled="isDisabled" type="number" :min="0" />
      </a-form-item>
      <a-form-item label="第三方单位" name="componyName" v-if="model.needRepair">
        <a-input v-model:value="model.componyName" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="联系方式" name="componyTel" v-if="model.needRepair">
        <a-input v-model:value="model.componyTel" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="model.remark" allowClear placeholder="请输入备注" :disabled="isDisabled" :rows="4" />
      </a-form-item>
      <a-form-item label="操作">
        <a-button @click="resetForm" v-show="!model.id">重置</a-button>
        <a-divider type="vertical" v-show="!model.id" />
        <a-button type="primary" html-type="submit" v-show="!model.id">提交保存</a-button>
        <a-button type="danger" v-show="model.id" @click="signbackOrder" v-auth="'order:signback'">退回</a-button>
        <a-divider type="vertical" v-show="model.id" v-auth="'order:signback'" />
        <a-button type="primary" v-show="model.id" @click="auditOrder" v-auth="'order:handle'">立即处理/结单</a-button>
        <a-divider type="vertical" v-show="model.id" v-auth="'order:handle'" />
        <a-button type="primary" v-show="model.id" @click="auditOrder">查看记录</a-button>
      </a-form-item>
    </a-form>
    <div></div>
    <!-- <a-timeline mode="right">
      <a-timeline-item>Create a services site 2015-09-01</a-timeline-item>
      <a-timeline-item>Solve initial network problems 2015-09-01</a-timeline-item>
      <a-timeline-item>Technical testing 2015-09-01</a-timeline-item>
      <a-timeline-item>Network problems being solved 2015-09-01</a-timeline-item>
    </a-timeline> -->
    <CommonAMap ref="commonAMap" @oks="getMapData" />
  </a-drawer>
</template>

<script lang="ts">
import { watch, ref, nextTick, defineComponent, getCurrentInstance, computed } from 'vue';
import { JDictSelectTag } from '/@/components/Form';
import { orderInfoApi, orderAddApi, orderModifyApi, confirmVistitApi, auditOrderApi, signbackOrderApi } from '/@/api/order';
import { projectListApi } from '@/api/project';
import CommonAMap from '/@/components/CommonAMap/index.vue';
import { useUserStore } from '/@/store/modules/user';
import { Empty, message } from 'ant-design-vue';
import { json } from 'stream/consumers';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';

export default defineComponent({
  components: { JDictSelectTag, CommonAMap },
  props: {
    odrerTypeList: {
      type: Object,
      defalut: [],
    },
    userList: {
      type: Object,
      defalut: [],
    },
    stationList: {
      type: Object,
      defalut: [],
    },
  },
  setup(props, { emit }) {
    const userStore = useUserStore();
    let { proxy } = getCurrentInstance();
    const glob = useGlobSetting();
    const ossAction = computed(() => `${glob.uploadUrl}/sys/common/upload`);
    // 文件列表
    let fileList = ref([]);
    const tokenHeader = { 'X-Access-Token': getToken() };
    let visible = ref(false);
    let model = ref({
      alarmId: '',
      stationCode: '',
      handleType: '',
      orderType: '',
      orderDetail: '',
      assignTo: '',
      needRepair: false,
      remark: '',
      attachments: '',
    });
    let regionList = ref([]);
    let rules = ref({
      stationCode: [{ required: true, message: '请选择归属站点' }],
      handleType: [{ required: true, message: '请选择处理方式' }],
      orderType: [{ required: true, message: '请选择工单类型' }],
    });

    let projectList = ref([]);

    let isDisabled = computed(() => {
      if (model.value.id) {
        return true;
      } else {
        return false;
      }
    });

    function getRegionData(data: []) {
      regionList.value = data;
    }

    function signbackOrder() {
      signbackOrderApi({ orderId: model.value.id }).then((res) => {
        visible.value = false;
        message.success('操作成功');
        emit('oks');
      });
    }

    function auditOrder() {
      auditOrderApi({ orderId: model.value.id }).then((res) => {
        visible.value = false;
        message.success('操作成功');
        emit('oks');
      });
    }

    /**
     * 初始化数据
     * @param {number} id
     */
    function init(id) {
      orderInfoApi({ id }).then((res) => {
        res['state'] = res['state'] + '';
        res['alarmState'] = res['alarmState'] + '';
        model.value = { ...res };
      });
    }

    function resetForm() {
      proxy.$refs.formRef.resetFields();
    }

    /**
     * 初始化项目列表
     */
    function initProjectList() {
      projectListApi({}).then((res) => {
        projectList.value = res;
      });
    }

    function onFinish() {
      let data = {
        ...model.value,
      };
      data.needRepair = Number(data.needRepair);
      if (!data['id']) {
        orderAddApi(data).then((res) => {
          proxy.$refs.formRef.resetFields();
          visible.value = false;
          message.success('新增成功');
          emit('oks');
        });
      } else {
        orderModifyApi(data).then((res) => {
          proxy.$refs.formRef.resetFields();
          visible.value = false;
          message.success('修改成功');
          emit('oks');
        });
      }
    }

    /**
     * 打开地图
     */
    function openMap() {
      proxy.$refs.commonAMap.visible = true;
      nextTick(() => {
        proxy.$refs.commonAMap.initMap(model.value);
      });
    }

    watch(
      () => visible.value,
      (v) => {
        if (v) {
          initProjectList();
        }
        if (!v) {
          model.value = {
            id: '',
            alarmId: '',
            handleType: '',
            orderType: '',
            orderDetail: '',
            assignTo: '',
            needRepair: '',
            remark: '',
          };
          delete model.value.id;
        }
      },
      { deep: true }
    );

    /**
     * 获取地图返回的经纬度
     */
    function getMapData({ longitue, latitude }) {
      Object.assign(model.value, {
        longitue,
        latitude,
      });
      AMap.plugin('AMap.Geocoder', () => {
        new AMap.Geocoder().getAddress([longitue, latitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            model.value.address = result.regeocode.formattedAddress;
          }
        });
      });
    }

    function showDrawer(data: {}) {
      visible.value = true;
      fileList.value = [];
      model.value.alarmId = data.id;
      model.value.stationCode = data.stationCode;
    }

    function confirmorder() {
      confirmVistitApi({ id: model.value.id }).then((res) => {
        message.success('操作成功');
      });
    }
    /**
     * 上传成功后组将成文件列表
     */
    function handleUploadChange(e) {
      console.log('e:', e);
      if (e.file.response) {
        let fileName = e.file.response.message;
        const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
        let url = `${glob.uploadUrl}/${fileName}`;
        model.value.attachments = url;
        // fileList.value.push({
        //   name: fileName,
        //   url,
        //   type: `.${fileExtension}`,
        // });
        // console.log(fileList.value);
      }
    }
    return {
      init,
      visible,
      model,
      rules,
      projectList,
      regionList,
      ossAction,
      fileList,
      tokenHeader,
      isDisabled,
      resetForm,
      onFinish,
      openMap,
      getMapData,
      getRegionData,
      showDrawer,
      confirmorder,
      auditOrder,
      handleUploadChange,
      signbackOrder,
    };
  },
});
</script>
